package com.hy.movie.wxpay.service;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONString;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hy.movie.config.HttpConfig;
import com.hy.movie.http.HttpUtil;
import com.hy.movie.model.entity.Order;
import com.hy.movie.wxpay.Amount;
import com.hy.movie.wxpay.Payer;
import com.hy.movie.wxpay.WxPlaceOrder;
import com.hy.movie.wxpay.WxPreOrderResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class WxPlaceOrderService {
    @Value("${wxmini.appId}")
    private String appId;
    @Value("${wxmini.matchId}")
    private String matchId;
    @Resource
    private HttpConfig httpConfig;
    private final static String RECEIVE = "/receive/data";
    private final static String ORDER_URL = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";

    /**
     * 微信下订单
     * @param order
     * @return
     */
    public WxPreOrderResponse placeOrder(Order order,String openId) throws JsonProcessingException,Exception{
        WxPlaceOrder wxPlaceOrder = new WxPlaceOrder();
        wxPlaceOrder.setAppid(appId);
        wxPlaceOrder.setMchid(matchId);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(order.getCinemaAddress()).append("-")
                .append(order.getCinemaName()).append("-").append(order.getHallName())
                .append("-").append(order.getMovieName());
        wxPlaceOrder.setDescription(stringBuilder.toString());
        wxPlaceOrder.setNotify_url(httpConfig.getHttpUrl()+RECEIVE);
        wxPlaceOrder.setOut_trade_no(order.getId().toString());
        Amount amount = new Amount();
        amount.setTotal((int)(order.getYuanjia() * 100));
        wxPlaceOrder.setAmount(amount);
        Payer payer = new Payer();
        payer.setOpenid(openId);
        wxPlaceOrder.setPayer(payer);
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(wxPlaceOrder);
        String result = HttpUtil.doPostJson(ORDER_URL, json);
        try {
            WxPreOrderResponse wxPreOrderResponse = mapper.readValue(result, WxPreOrderResponse.class);
            return wxPreOrderResponse;
        }catch (Exception e){
            throw new Exception(result);
        }
    }
}
